package logic

import (
	"context"

	"googee/common/errorx"
	"googee/common/utils"
	"googee/service/search/api/internal/svc"
	"googee/service/search/api/internal/types"

	"github.com/meilisearch/meilisearch-go"
	"github.com/zeromicro/go-zero/core/logx"
)

type SearchLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewSearchLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SearchLogic {
	return &SearchLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

/*
设置过滤器
curl \
  -X POST 'http://localhost:7700/indexes/user/settings/filterable-attributes' \
  -H 'Content-Type: application/json' \
  --header 'Authorization: Bearer fRUTHN1Ir8' \
  --data-binary '[
    "gender"
  ]'


curl \
  -X GET 'http://localhost:7700/indexes/user/settings/filterable-attributes' \
  --header 'Authorization: Bearer fRUTHN1Ir8'

*/
func (l *SearchLogic) Search(req *types.SearchReq) (resp *types.SearchReply, err error) {
	resp = &types.SearchReply{}
	request := &meilisearch.SearchRequest{
		Limit:  utils.MinInt64(50, req.Limit),
		Offset: req.Offset,
		// Filter: `gender="M"`,
	}

	search, err := l.svcCtx.MeiliClient.Index(req.Category).Search(req.Content, request)
	if err != nil {
		logx.Errorf("错误信息:%v", err)
		return nil, errorx.NewCodeErrorNoMsg(errorx.INTERNAL_ERROR)
	}
	resp.Data.Hits = search.Hits
	resp.Data.Offset = search.Offset + int64(len(search.Hits))
	resp.Data.Limit = search.Limit
	return
}
